<template>
  <div class="">
    <div class="center">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
        <el-form-item label="活动名称" prop="activityName">
          <el-input
            maxlength="16"
            v-model.trim="queryParams.activityName"
            placeholder="请输入活动名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="选择时间区间" prop="time">
          <el-date-picker
            style="width: 240px"
            v-model="queryParams.time"
            type="daterange"
            format="YYYY-MM-DD"
            value-format="x"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" fit-input-width clearable placeholder="请选择">
            <el-option label="全部状态" value=""></el-option>
            <el-option
              v-for="item in STATUS_OPTIONS"
              :key="item.status"
              :label="item.label"
              :value="item.status"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="城市标签" prop="cityName">
          <el-select
            v-model="queryParams.cityName"
            @change="handleQuery"
            fit-input-width
            placeholder="请选择"
          >
            <el-option
              v-for="item in cityNameOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动范围" prop="positionName">
          <el-select
            v-model="queryParams.positionName"
            fit-input-width
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in positionOptions"
              :key="item.positonName"
              :label="item.positonName"
              :value="item.positonName"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['marketing:invitation:add']"
            icon="Plus"
            type="primary"
            @click="handleAdd"
          >
            新建
          </el-button>
        </el-col>

        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" size="default" index :data="dataList">
        <el-table-column
          label="活动名称"
          min-width="150px"
          align="center"
          prop="activityName"
          show-overflow-tooltip
        />
        <el-table-column label="城市标签" align="center" prop="cityName" show-overflow-tooltip />
        <el-table-column label="活动时间" width="260px" align="center">
          <template #default="{ row }">
            <div>
              {{ row.startTime + '~\n' + row.endTime }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="新增用户数" min-width="100px" align="center" prop="count" />
        <el-table-column label="邀请奖励" min-width="100px" align="center" prop="couponName" />
        <el-table-column label="状态" width="70px" align="center" prop="sttaus">
          <template #default="{ row }">
            <div>
              <el-link :underline="false" :type="getStatusType(row.status)">{{
                getStatusLabel(row.status)
              }}</el-link>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="活动范围" min-width="100px" align="center" prop="pointLabel">
          <template #default="{ row }">
            <span v-if="row?.position == 1 || row?.position == 3">{{
              row?.position == 1 ? '普通全部' : '特殊全部'
            }}</span>
            <el-tooltip placement="top" v-else>
              <template #content>
                <div class="pointLabelList">
                  <span v-for="i in row?.positionNames" :key="i"> {{ i }}</span>
                </div>
              </template>
              <el-button type="primary" link>
                {{ row?.position === 2 ? '普通指定点位' : '特殊指定点位' }}</el-button
              >
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="邀请记录" align="center" width="80" fixed="right">
          <template #default="{ row }">
            <el-link
              v-hasPermi="['marketing:invitation:records']"
              :underline="false"
              type="primary"
              @click="handleRecords(row.id)"
              >查看</el-link
            >
          </template>
        </el-table-column>
        <el-table-column label="参与详情" align="center" width="80" fixed="right">
          <template #default="{ row }">
            <el-link
              v-hasPermi="['marketing:invitation:involved']"
              :underline="false"
              type="primary"
              @click="handleJoin(row)"
              >查看</el-link
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="{ row }">
            <el-link
              v-hasPermi="['marketing:invitation:delete']"
              v-if="row.status === 0"
              style="margin-right: 6px"
              :underline="false"
              type="danger"
              @click="handleDelete(row)"
              >删除
            </el-link>
            <el-link
              v-hasPermi="['marketing:invitation:expire']"
              v-if="row.status !== 0"
              style="margin-right: 6px"
              :underline="false"
              type="primary"
              @click="handleExpire(row)"
              >失效
            </el-link>
            <el-link
              v-hasPermi="['marketing:invitation:detail']"
              style="margin-right: 6px"
              :underline="false"
              type="primary"
              @click="handleDetail(row)"
              >详情
            </el-link>
            <el-link
              v-if="row.status === 4 || row.status === 1"
              v-hasPermi="['marketing:invitation:edit']"
              :underline="false"
              type="primary"
              @click="handleEdit(row)"
              >编辑</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-right: 10px">
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <addDialog ref="addRef" :title="title" @refresh="getList" />
    <detailDialog ref="detailRef" :title="title" />
    <recordsDialog ref="recordsRef" />
    <joinDialog ref="joinRef" />
  </div>
</template>

<script setup>
import addDialog from './cpts/addDialog.vue'
import detailDialog from './cpts/detailDialog.vue'
import recordsDialog from './cpts/recordsDialog.vue'
import joinDialog from './cpts/joinDialog.vue'

import { getPositionListApi } from '@/api/marketing/activity'
import { getInvitationListApi, updateInvitationApi } from '@/api/marketing/invitation'
import useGlobalStore from '@/store/modules/global'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => {
  queryParams.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
  return globalStore.myCityList
})
const positionOptions = ref([])
const title = ref('')
const queryRef = ref(null)
const showSearch = ref(true)
const STATUS_OPTIONS = [
  {
    label: '进行中',
    status: 1,
    type: 'success'
  },
  {
    label: '已失效',
    status: 0,
    type: 'info'
  },
  {
    label: '已过期',
    status: 2,
    type: 'info'
  },
  {
    label: '待开始',
    status: 4,
    type: 'warning'
  }
]

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  activityName: '',
  time: '',
  status: '',
  cityName: '',
  positionName: ''
})

const total = ref(0)
const dataList = ref([])
const loading = ref(false)

function getStatusType(status) {
  return STATUS_OPTIONS.find((i) => {
    return i.status === status
  })?.type
}

function getStatusLabel(status) {
  return STATUS_OPTIONS.find((i) => {
    return i.status === status
  })?.label
}

function getList() {
  console.log('queryPrams.cityName', queryParams.cityName)
  loading.value = false
  const params = {
    ...queryParams,
    startTime: queryParams.time?.length ? queryParams.time[0] : '',
    endTime: queryParams.time?.length ? queryParams.time[1] : ''
  }
  delete params.time
  getInvitationListApi(params)
    .then((res) => {
      loading.value = false
      dataList.value = res?.data?.rows || []
      total.value = res?.data?.total || 0
    })
    .catch(() => {
      loading.value = false
      dataList.value = []
      total.value = 0
    })
}

// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  getPositions()
  getList()
}

// 重置
function resetQuery() {
  queryRef.value.resetFields()
  handleQuery()
}
function getPositions() {
  getPositionListApi({ cityName: queryParams.cityName }).then((res) => {
    positionOptions.value = res?.data || []
  })
}
// 新建
const addRef = ref(null)
function handleAdd() {
  title.value = '邀请活动设置'
  addRef.value.init(queryParams.cityName)
}

// 邀请记录
const recordsRef = ref(null)
function handleRecords(id) {
  recordsRef.value.init(id)
}
// 参与详情
const joinRef = ref(null)
function handleJoin(row) {
  joinRef.value.init(row.id)
}

// 失效 删除
function handleDelete(row) {
  ElMessageBox.confirm('活动记录将会被删除', '操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  })
    .then(() => {
      updateInvitationApi({ marActivityId: row.id, status: 3 }).then(() => {
        ElMessage({
          type: 'success',
          message: '操作成功'
        })
        handleQuery()
      })
    })
    .catch(() => {})
}
function handleExpire(row) {
  ElMessageBox.confirm('活动将会被强制失效', '操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  })
    .then(() => {
      updateInvitationApi({ marActivityId: row.id, status: 0 }).then(() => {
        ElMessage({
          type: 'success',
          message: '操作成功'
        })
        getList()
      })
    })
    .catch(() => {})
}

// 详情
const detailRef = ref(null)
function handleDetail(row) {
  title.value = '邀请活动详情'
  addRef.value.init(row.cityName, row.id)
}
/**编辑 */
function handleEdit(row) {
  title.value = '邀请活动编辑'
  addRef.value.init(row.cityName, row.id)
}
onMounted(() => {
  queryParams.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
  getPositions()
  getList()
})
</script>

<style lang="scss" scoped>
.center {
  padding: 20px;
  .actions {
    align-items: center;
    display: flex;
  }
}
.name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}
.pointLabelList {
  max-width: 600px;
  word-wrap: break-word;
  white-space: normal;
}
</style>
